export const checkLogin = () => {
  const token = getUrlParam('token')
  return token
}

// 获取地址参数
export const getUrlParam = (key, url = window.location.hash) => {
  let obj = {},
    index = url.indexOf('?'),
    params = url.substr(index + 1)
  if (index != -1) {
    let parr = params.split('&')
    for (let i of parr) {
      let arr = i.split('=')
      obj[arr[0]] = arr[1]
    }
  }
  return obj[key] || null
}

export const getAuthorization = () => {
  let token =
    JSON.parse(localStorage.getItem('Access-Token')) ||
    'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvY2hpZGlhbi5jeXl2aXAuY29tIiwiaWF0IjoxNjQ3MjM5NzcwLCJleHAiOjE2NDczMjYxNzAsImFkbWluX2lkIjoxLCJ1c2VybmFtZSI6ImFkbWluIiwic3RvcmVfaWQiOiIxMDQiLCJyb2xlcyI6InN1cGVyX2FkbWluIn0.yBoHwse4YMM40G_hKQ9iK-qHFcQLNMai-bAAyoSoL5I'
  return token
}

// 节流
export const throttle = (fn, time) => {
  let cd = true
  return function (...args) {
    if (!cd) return
    fn(this, ...args)
    cd = false
    setTimeout(() => {
      cd = true
    }, time)
  }
}

// 防抖
export const debounce = (fn, time) => {
  let timer = null
  return function (...args) {
    if (timer) {
      // 每次进来先结束计时
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn(this, ...args)
    }, time)
  }
}

// 获取链接参数
const getQueryString = (link, name) => {
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'),
    index = link.indexOf('?')

  if (index === -1) {
    return null
  }

  let r = link.substr(index + 1).match(reg)

  if (r != null) {
    return unescape(r[2])
  }
  return null
}

// 链接选择器拼凑地址
export const getDiyURLText = (obj = null, item = null) => {
  if (!obj) return ''

  let newObj = JSON.parse(JSON.stringify(obj)),
    { link, params } = newObj,
    str = `${link}`

  if (str.indexOf('?') === -1 && params && params.length) {
    str += '?'
  }

  if (item) {
    params.forEach((el) => {
      if (el.valueKey) {
        let value = item[el.valueKey]
        if (!value) return this.$message.error('该属性不存在！')
        el.value = value
      }
    })
  }

  if (params && params.length) {
    params.forEach(({ key, value }) => {
      if (str.indexOf(key) !== -1) {
        if (['tel?', 'web?'].includes(str)) {
          str = str + `${key}=${value}`
          return
        }

        let olDstr = `${key}=${getQueryString(str, key)}`
        str = str.replace(olDstr, `${key}=${value}`)
      } else {
        str += `${key}=${value || ''}&`
      }
    })
  }

  if (/&$/.test(str)) {
    str = str.slice(0, str.length - 1)
  }

  newObj.link = str
  return newObj
}

/**
 * @param {Number} len uuid的长度
 * @param {Boolean} firstU 将返回的首字母置为"u"
 * @param {Nubmer} radix 生成uuid的基数(意味着返回的字符串都是这个基数),2-二进制,8-八进制,10-十进制,16-十六进制
 */
export const guid = function (len = 32, firstU = true, radix = null) {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  const uuid = []
  radix = radix || chars.length

  if (len) {
    // 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位
    for (let i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)]
  } else {
    let r
    // rfc4122标准要求返回的uuid中,某些位为固定的字符
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
    uuid[14] = '4'

    for (let i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16)
        uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r]
      }
    }
  }
  // 移除第一个字符,并用u替代,因为第一个字符为数值时,该guuid不能用作id或者class
  if (firstU) {
    uuid.shift()
    return `u${uuid.join('')}`
  }
  return uuid.join('')
}

/**
 * @param {Date} date
 * @param {String} fmt yyyy-MM-dd hh:mm:ss
 * @returns
 */
export function formatDate(date, fmt) {
  if (typeof date == 'string') {
    return date
  }

  if (!fmt) fmt = 'yyyy-MM-dd hh:mm:ss'

  if (!date || date == null) return null
  let o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds(), // 毫秒
  }
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
  }
  return fmt
}
